<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="50%"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './role.data';
  import { useMessage } from '/@/hooks/web/useMessage';

  // import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  // import { BasicTree, TreeItem } from '/@/components/Tree';
  import { BasicModal, useModalInner } from '/@/components/Modal';

  import { addRoleApi, updateRoleApi, getRoleInfoApi } from '/@/api/admin/role';

  export default defineComponent({
    name: 'RoleDrawer',
    components: { BasicModal, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);

      let updateInfo = {};
      const { createMessage } = useMessage();
      // const treeData = ref<TreeItem[]>([]);

      const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
        labelWidth: 90,
        baseColProps: { span: 24 },
        schemas: formSchema,
        showActionButtonGroup: false,
      });
      const [registerDrawer, { setModalProps, closeModal }] = useModalInner(async (data) => {
        resetFields();
        setModalProps({ confirmLoading: false });

        isUpdate.value = !!data?.isUpdate;

        updateSchema([
          {
            field: 'roleCode',
            label: '角色标识',
            dynamicDisabled: unref(isUpdate),
            component: 'Input',
          },
          {
            field: 'menu',
            ifShow: unref(isUpdate),
          },
        ]);
        if (unref(isUpdate)) {
          const res = await getRoleInfoApi(data?.record.roleId as string);
          updateInfo = res;

          const { userList } = res;
          if (userList && userList.length) {
            res.userList = userList.map((item) => item.userId);
          }
          setFieldsValue({
            ...res,
          });
        }
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增角色' : '编辑角色'));

      async function handleSubmit() {
        try {
          const values = await validate();
          setModalProps({ confirmLoading: true });
          if (values.userList) {
            const userList = values.userList.map((item) => {
              return { userId: item };
            });
            values.userList = userList;
          }
          const params = Object.assign(updateInfo, values);
          const apiFn = unref(isUpdate) ? updateRoleApi : addRoleApi;
          await apiFn(params);

          closeModal();
          createMessage.success('操作成功');
          emit('success');
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      return {
        registerDrawer,
        registerForm,
        getTitle,
        handleSubmit,
      };
    },
  });
</script>
